<template>
  <AcceptHandleHeadComponent
    ref="acceptHandleHeadRef"
    :ucolumns="ucolumns"
    :type="LableTitle.correctGroup"
    :needMoreQuery="true"
    :showCaseNoQuery="false"
    @myEvent="myEvent"
    @onSearch="search"
    @onReset="reQuery"
  >
    <div slot="headLeft">
      <a-form-item style="display: flex; margin-bottom: 0px">
        <a-input v-model="queryParam.f_name" placeholder="请输入分组名称" allowClear style="height: 40px" />
      </a-form-item>
    </div>

    <div slot="headRight" style="margin-right: 30px">
      <a-button type="primary" class="btn_primary_color" style="margin-left: 12px" @click="addGroup">新增分组</a-button>
    </div>

    <!-- 其他查询条件 -->
    <div slot="more">
      <a-form layout="inline" class="accept_more_operate_moreForm">
        <a-collapse v-model="collapseKey" class="accept_more_operate_moreForm_collapse" >
          <a-collapse-panel  :show-arrow="false" disabled key="1" style="font-weight: bold">
            <div slot="header" class="accept_more_operate_moreForm_collapse_head">
              <a-row :gutter="48" style="width: 100%">
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="创建人">
                    <a-input v-model="queryParam.f_createusername" placeholder="请输入创建人" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => {}" :md="12" :sm="24">
                  <a-form-item label="创建时间">
                    <a-date-picker
                      v-model="queryParam.f_createtime"
                      :style="{ width: 'calc(50% - 12px)' }"
                      placeholder="开始日期"
                      format="YYYY-MM-DD"
                      allowClear
                      @change="subtimeListen()"
                    />
                    ~
                    <a-date-picker
                      v-model="queryParam.f_createtime_01"
                      :style="{ width: 'calc(50% - 12px)' }"
                      placeholder="结束日期"
                      format="YYYY-MM-DD"
                      allowClear
                      @change="subtimeListen()"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </div>

    <template slot="content">
      <!-- 表格数据 -->
      <a-table
        :scroll="scroll"
        :columns="ucolumns"
        :data-source="listData"
        :pagination="upagination"
        :loading="loading"
        rowKey="id"
        @change="tableChange"
        size="middle"
        :bordered="ubordered"
        :rowClassName="rowClassName"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
        </span>
        <!-- 分组名-->
        <div slot="nameSlot" slot-scope="name" style="text-align: left">
          {{ name }}
        </div>
        <!--描述-->
        <div slot="remarkSlot" slot-scope="remark" class="beyond_hiding" style="width: 100%; text-align: left">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{ remark }}</span>
            </template>
            {{ remark }}
          </a-tooltip>
        </div>

        <span slot="operation" slot-scope="text, record">
          <template>
            <a href="javascript:;" @click="editGroup(record)">编辑</a>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="deleteGroup(record)">删除</a>
          </template>
        </span>

        <a-table
          slot="expandedRowRender"
          slot-scope="fatherRecord"
          :columns="innerColumns"
          :data-source="fatherRecord.groupPersons"
          :pagination="false"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ parseInt(index) + 1 }}
          </span>

          <div slot="genderSlot" slot-scope="gender" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ genderLabel(gender) }}</span>
              </template>
              {{ genderLabel(gender) }}
            </a-tooltip>
          </div>
          <!--民族-->
          <div
            slot="nation_textSlot"
            slot-scope="nation_text"
            class="beyond_hiding"
            style="width: 100%; text-align: left"
          >
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ nation_text }}</span>
              </template>
              {{ nation_text }}
            </a-tooltip>
          </div>

          <div slot="crctypeSlot" slot-scope="crctype" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crctypeLabel(crctype) }}</span>
              </template>
              {{ crctypeLabel(crctype) }}
            </a-tooltip>
          </div>

          <div slot="controltypeSlot" slot-scope="controltype" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ controltypeLabel(controltype) }}</span>
              </template>
              {{ controltypeLabel(controltype) }}
            </a-tooltip>
          </div>

          <div slot="nameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-popover v-if="record.avatar">
              <template slot="content">
                <a-avatar :size="80" v-if="record.avatar" :src="record.avatar" />
              </template>
              {{ record.name }}
            </a-popover>
            <span v-else>
              {{ record.name }}
            </span>
          </div>

          <div slot="crimeSlot" slot-scope="crime" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crime }}</span>
              </template>
              {{ crime }}
            </a-tooltip>
          </div>

          <div slot="cardnoSlot" slot-scope="cardno" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ cardno }}</span>
              </template>
              {{ cardno }}
            </a-tooltip>
          </div>

          <template slot="createusernameSlot" slot-scope="createusername">
            <a-tag><a-icon type="user" />{{ createusername }} </a-tag>
          </template>

          <!--矫正期限-->
          <div slot="stimelongSlot" slot-scope="stimelong" style="text-align: right">
            {{ stimelong }}
          </div>

          <div slot="startdateSlot" slot-scope="startdate" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ startdate }}</span>
              </template>
              {{ startdate }}
            </a-tooltip>
          </div>

          <div slot="enddateSlot" slot-scope="enddate" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ enddate }}</span>
              </template>
              {{ enddate }}
            </a-tooltip>
          </div>

          <div slot="deptidSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%; text-align: left">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.deptname }}</span>
              </template>
              {{ record.deptname }}
            </a-tooltip>
          </div>

          <span slot="operation" slot-scope="text, record">
            <template>
              <a href="javascript:;" @click="deleteGroupByPersonId(record, fatherRecord)">删除</a>
            </template>
          </span>
        </a-table>
      </a-table>

      <a-modal
        :title="infoForm.isEdit ? '编辑社矫分组' : '添加社矫分组'"
        width="40%"
        :footer="null"
        v-model="editVisible"
        :body-style="{ paddingBottom: '30px' }"
        @close="editVisible = false"
        destroyOnClose
      >
        <CorrectGroupAdd
          ref="CorrectGroupAddRef"
          @close="editVisible = false"
          @reloadList="queryList"
          :infoForm="infoForm"
        ></CorrectGroupAdd>
      </a-modal>
    </template>
  </AcceptHandleHeadComponent>
</template>

<script>
import { pageQuery, deleteGroup, findAllLawDeparts } from '@/api/correction/crc_group.js'
import { deleteByPersonId } from '@/api/correction/crc_group_person.js'
import { Tp_genderList } from '@/enumeration/Tp_gender'
import { Tp_crc_userList } from '@/enumeration/correction/Tp_crc_user'
import { Tp_crc_ctrlList } from '@/enumeration/correction/Tp_crc_ctrl'
import AcceptHandleHeadComponent from '@/views/accept/component/AcceptHandleHeadComponent.vue'
import { LableTitle } from '@/enumeration/LableTitle.js'
import { Decrypt } from '@/enumeration/SM.js'

const ucolumns = [
  {
    title: '序号',
    width: 50,
    key: 'index',
    align: 'center',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '分组名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
    width: 250,
    scopedSlots: { customRender: 'nameSlot' }
  },
  {
    title: '描述',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
    width: 450,
    scopedSlots: { customRender: 'remarkSlot' }
  },
  {
    title: '创建人名称',
    dataIndex: 'createusername',
    key: 'createusername',
    width: 300,
    align: 'center',
    scopedSlots: { customRender: 'createusernameSlot' }
  },
  {
    title: '创建时间',
    key: 'createtime',
    width: 300,
    align: 'center',
    dataIndex: 'createtime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 300,
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]
const innerColumns = [
  {
    title: '序号',
    key: 'index',
    align: 'center',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
    scopedSlots: { customRender: 'nameSlot' }
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    align: 'center',
    scopedSlots: { customRender: 'genderSlot' }
  },
  {
    title: '民族',
    dataIndex: 'nation_text',
    key: 'nation_text',
    align: 'center',
    scopedSlots: { customRender: 'nation_textSlot' }
  },
  {
    title: '矫正类别',
    dataIndex: 'crctype',
    key: 'crctype',
    align: 'center',
    scopedSlots: { customRender: 'crctypeSlot' }
  },
  {
    title: '管控级别',
    dataIndex: 'controltype',
    key: 'controltype',
    align: 'center',
    scopedSlots: { customRender: 'controltypeSlot' }
  },
  {
    title: '罪名',
    dataIndex: 'crime',
    key: 'crime',
    align: 'center',
    scopedSlots: { customRender: 'crimeSlot' }
  },
  {
    title: '身份证号',
    key: 'cardno',
    dataIndex: 'cardno',
    align: 'center',
    scopedSlots: { customRender: 'cardnoSlot' }
  },
  {
    title: '联系号码',
    key: 'phone',
    dataIndex: 'phone',
    align: 'center'
  },
  {
    title: '矫正期限',
    dataIndex: 'timelong',
    key: 'timelong',
    align: 'center',
    scopedSlots: { customRender: 'stimelongSlot' }
  },
  {
    title: '矫正开始日期',
    dataIndex: 'startdate',
    key: 'startdate',
    align: 'center',
    scopedSlots: { customRender: 'startdateSlot' }
  },
  {
    title: '矫正结束日期',
    dataIndex: 'enddate',
    key: 'enddate',
    align: 'center',
    scopedSlots: { customRender: 'enddateSlot' }
  },
  {
    title: '所在司法所',
    dataIndex: 'deptid',
    key: 'deptid',
    align: 'center',
    scopedSlots: { customRender: 'deptidSlot' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  data () {
    return {
      Tp_genderList: Tp_genderList,
      Tp_crc_userList: Tp_crc_userList,
      Tp_crc_ctrlList: Tp_crc_ctrlList,
      ucolumns: ucolumns,
      listData: [],
      innerColumns: innerColumns,
      queryParam: {
        f_name: undefined, // 分组名称
        f_createusername: undefined, // 创建人名称
        f_createtime: undefined, // 创建时间
        f_createtime_01: undefined, // 创建结束时间
        pageNumber: 1,
        pageSize: 20,
        sort: 'createtime',
        order: 'desc'
      },
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      editVisible: false,

      infoForm: {
        id: undefined,
        name: undefined, // 分组名称
        remark: undefined, // 描述
        personIds: [], // 组内人员
        isEdit: false
      },
      lawDeparts: [], // 司法所信息

      LableTitle: LableTitle,
      header: undefined,
      tableCountKey: 0,
      collapseKey: [], // 折叠面板key
      scroll: { x: 1000, y: 410 }
    }
  },
  components: {
    HEADERDEFINITION: () => import('@/views/customComponents/headerDefinition.vue'),
    CorrectGroupAdd: () => import('@/views/correction//manager/CorrectGroupAdd.vue'),
    AcceptHandleHeadComponent
  },
  async created () {
    this.queryList()
    const res = await findAllLawDeparts()
    if (res.code === 0) {
      this.lawDeparts = res.data
    } else {
      this.$message.error('查询全部司法所信息异常')
    }
  },
  methods: {
    myEvent (e) {
      if (e) {
        this.scroll.y = this.scroll.y + e
      } else {
        this.scroll.y = 410
      }
    },
    // 搜索
    search () {
      this.queryParam.pageNumber = 1
      this.queryList()
    },
    // // 重置表头方法
    // resetting () {
    //   this.$refs.headerDefRef.f_resetting()
    // },
    // // 子组件回调函数, 重置表头
    // s_setColumns (columns) {
    //   this.ucolumns = columns
    // },
    // // 显示自定义表头组件
    // showHeaderDef (e) {
    //   this.$refs.headerDefRef.f_init(e)
    // },
    subtimeListen () {
      if (
        this.queryParam.f_createtime > this.queryParam.f_createtime_01 &&
        this.queryParam.f_createtime &&
        this.queryParam.f_createtime_01
      ) {
        this.queryParam.f_createtime = undefined
      }
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      // eslint-disable-next-line no-unused-expressions
      this.queryParam = {
        f_name: undefined, // 分组名称
        f_createusername: undefined, // 创建人名称
        f_createtime: undefined, // 创建时间
        f_createtime_01: undefined, // 创建结束时间
        pageNumber: 1,
        pageSize: 20,
        sort: 'createtime',
        order: 'desc'
      }
      this.queryList()
    },
    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },

    getCpQueryParam () {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.f_startdate?.format) {
        cpQueryParam.f_startdate = this.queryParam.f_startdate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_startdate_01?.format) {
        cpQueryParam.f_startdate_01 = this.queryParam.f_startdate_01.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_enddate?.format) {
        cpQueryParam.f_enddate = this.queryParam.f_enddate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_enddate_01?.format) {
        cpQueryParam.f_enddate_01 = this.queryParam.f_enddate_01.format('YYYY-MM-DD') + ' 00:00:00'
      }
      return cpQueryParam
    },

    /**
     * 删除社矫分组
     */
    deleteGroup (record) {
      this.$confirm({
        title: '提醒',
        content: '是否要删除当前的社矫分组？',
        okText: '是',
        cancelText: '否',
        onOk: () => {
          deleteGroup({ id: record.id }).then(res => {
            if (res.code !== 0) {
              this.$message.error('删除失败')
            } else {
              this.$message.success('删除成功')
              this.queryList()
            }
          })
        }
      })
    },
    /**
     * 删除社矫对象和分组的关联关系
     */
    deleteGroupByPersonId (record, fatherRecord) {
      this.$confirm({
        title: '提醒',
        content: '是否要删除当前分组下的社矫对象？',
        okText: '是',
        cancelText: '否',
        onOk: () => {
          deleteByPersonId({ personId: record.id, groupId: fatherRecord.id }).then(res => {
            if (res.code !== 0) {
              this.$message.error('删除失败')
            } else {
              this.$message.success('删除成功')
              this.queryList()
            }
          })
        }
      })
    },
    addGroup () {
      this.editVisible = true
      this.infoForm = {
        id: undefined,
        name: undefined, // 分组名称
        remark: undefined, // 描述
        personIds: [], // 组内人员
        isEdit: false
      }
      this.infoForm.isEdit = false
    },
    editGroup (record) {
      this.editVisible = true
      this.infoForm = JSON.parse(JSON.stringify(record))
      for (const key in record) {
        this.$set(this.infoForm, key, record[key])
      }
      const personIds = []
      if (record.groupPersons && record.groupPersons.length > 0) {
        for (const element of record.groupPersons) {
          personIds.push(element.id)
        }
      }
      this.$set(this.infoForm, 'personIds', personIds)
      this.infoForm.isEdit = true
    },

    queryList () {
      const queryParam = this.getCpQueryParam()
      this.loading = true
      pageQuery(queryParam)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('获取数据失败')
          } else {
            this.listData = res.data.records
            console.log('获取分组数据：', res.data.records);
            this.listData = res.data.records.map(item => {
              if (item.groupPersons) {
                // 直接修改 item.groupPersons 数组
                item.groupPersons = item.groupPersons.map(e => {
                  e.cardno = Decrypt(e.cardno);
                  e.name = Decrypt(e.name);
                  e.phone = Decrypt(e.phone);
                  return e;
                });
              }
              return item;
            });
            this.upagination.total = res.data.total
            this.upagination.current = res.data.current
            this.upagination.pageSize = res.data.size
          }
        })
        .catch(err => {
          this.listData = []
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    genderLabel (val) {
      // eslint-disable-next-line camelcase
      for (const key in Tp_genderList) {
        if (Tp_genderList[key].value === val) {
          return Tp_genderList[key].name
        }
      }
      return val
    },
    crctypeLabel (val) {
      // eslint-disable-next-line camelcase
      for (const key in Tp_crc_userList) {
        if (Tp_crc_userList[key].value === val) {
          return Tp_crc_userList[key].name
        }
      }
      return val
    },
    controltypeLabel (val) {
      for (const key in Tp_crc_ctrlList) {
        if (Tp_crc_ctrlList[key].value === val) {
          return Tp_crc_ctrlList[key].name
        }
      }
      return val
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';

::v-deep .ant-table-thead > tr > th {
  font-weight: 600;
}
.formArea {
  margin-bottom: 30px;
}

.headerdefBox img {
  height: 20px;
  width: 20px;
}
.headerdefBox {
  // border: 1px solid red;
  margin: 0 10px 10px 0;
  display: flex;
  justify-content: end;
}

.collapseArea {
  border: none;
  .ant-collapse-item {
    border-bottom: none;
  }
  /deep/.ant-collapse-content {
    border-top: none;
  }
}
/deep/ .ant-collapse-header {
  background-color: #fff;
}
.collapseArea_header {
  .ant-form-item {
    margin-bottom: 0;
  }
}

.collapseArea_body {
  padding-top: 10px;
  padding: 0 20px 0 0px;
}
</style>
